package com.ruicar.afs.cloud.afscase.dispatch.component;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.util.Collection;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author cheng.bi
 * 任务组件
 */
@Component
public class BaseComponent {

    @Autowired
    private ApplicationContext applicationContext;


    /**
     * 获取指定的父类下所有的实现类，并且筛选出含有指定的annotation
     *
     * @param <T>
     * @param manager
     * @param annotation
     * @return
     */
    protected <T> Collection<T> getBeansWithAnnotation(Class<T> manager, Class<? extends Annotation> annotation) {
        Collection<T> collection = applicationContext.getBeansOfType(manager).values().stream()
                .filter(managers -> (managers.getClass()).getAnnotation(annotation) != null)
                .collect(Collectors.toList());

        return collection;
    }

    protected <T> Map<String, T> getBeanMapWithAnnotation(Class<T> manager, Class<? extends Annotation> annotation) {

        Map<String, T> collection = applicationContext.getBeansOfType(manager).entrySet().stream()
                .filter(service -> service.getValue().getClass().getAnnotation(annotation) != null)
                .collect(Collectors.toMap(
                        s -> s.getKey(),
                        s -> s.getValue()
                ));


        return collection;


    }

}
